var allPro = null;
var allBase = null;
$(function () {
    $.when( $.get(baseURL + 'bss/dpoint/select?pGuid='+ GetUrlParam("guid"), function (r) {
            allPro = r.returnlist;
		}),
		$.get(baseURL + 'bss/apbase/select?ourid=isok', function (r) {
			allBase = r.returnlist;
		}),
        getBigtype()

    ).done(
    $("#jqGrid").jqGrid({
        url: baseURL + 'bss/dmaterialbuy/list?dpGuid='+ GetUrlParam("dpguid")+'&pGuid='+ GetUrlParam("pguid"),
        datatype: "json",
        colModel: [			
			{ label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
			{hidden:true, label: '所属项目ID', name: 'pGuid', index: 'p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allBase) {
                        if (cellvalue == allBase[d].guid) return allBase[d].pBName;
                    }
                }
			},
			{ label: '安装位置', name: 'pPGuid', index: 'p_p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allPro) {
                        if (cellvalue == allPro[d].guid) return allPro[d].pPCode;
                    }
                }
			},
			{ hidden:true,label: '关联材料信息库ID', name: 'mMGuid', index: 'm_m_guid', width: 80,hidden:true },
			{ hidden:true,label: '材料大类', name: 'mBBigtype', index: 'm_b_bigtype', width: 80 },
			{ label: '材料类型', name: 'mBMidtype', index: 'm_b_midtype', width: 80 },
			{ label: '材料名称', name: 'mBName', index: 'm_b_name', width: 80 }, 			
			{ label: '主要参数', name: 'mBParameter', index: 'm_b_parameter', width: 80 }, 			
			{ label: '单重（kg）', name: 'mBWeight', index: 'm_b_weight', width: 80 }, 			
			{ label: '单价（元）', name: 'mBPrice', index: 'm_b_price', width: 80 }, 			
			{ label: '购置单位', name: 'mBUnit', index: 'm_b_unit', width: 80 }, 			
			{ label: '数量', name: 'mBCount', index: 'm_b_count', width: 80 }, 			
			{ label: '合重（kg）', name: 'mBWeightall', index: 'm_b_weightall', width: 80 }, 			
			{ label: '合价（元）', name: 'mBPriceall', index: 'm_b_priceall', width: 80 }, 			
			{ label: '数据来源    系统和人工', name: 'mBSource', index: 'm_b_source', width: 80},
			{ hidden:true,label: '数据状态', name: 'mBDatastate', index: 'm_b_datastate', width: 80,hidden:true },
			{hidden:true, label: '设备标签', name: 'dLabel', index: 'd_label', width: 80 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    })
	)
});
function getBigtype() {
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getBigtype",
        success:function(data){
            for(var i=0;i<data.bigtype.length;i++){
                var sel = document.getElementById('mBigtype');
                sel.options.add(new Option(""+data.bigtype[i].mBigtype+"",""+data.bigtype[i].mBigtype+""));
            }
        }
    });
}

//  大类被选中后触发事件查询对应大类下的中类
function chooseBigtype() {

    var mt = $("#mBigtype").val();
    var sel = document.getElementById('mMidtype');
    sel.options.length=0;
    if(mt==""){
        mt = bigtype;
    }
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getMidtype?mBigtype="+mt,
        success:function(data){
            for(var i=0;i<data.midtype.length;i++){
                sel.options.add(new Option(""+data.midtype[i].mMidtype+"",""+data.midtype[i].mMidtype+""));
            }
        }
    });
}


var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        q:{
            qLabel:null,
            qName:null,
            names:null,
            lables:null
        },
		dMaterialBuy: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dMaterialBuy = {};
            vm.getDept();
		},
		update: function (event) {
			var guid = getSelectedRow();
			if(guid == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(guid)
		},
		saveOrUpdate: function (event) {
			var url = vm.dMaterialBuy.guid == null ? "bss/dmaterialbuy/save" : "bss/dmaterialbuy/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.dMaterialBuy),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var guids = getSelectedRows();
			if(guids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "bss/dmaterialbuy/delete",
                    contentType: "application/json",
				    data: JSON.stringify(guids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(guid){
			$.get(baseURL + "bss/dmaterialbuy/info/"+guid, function(r){
                vm.dMaterialBuy = r.dMaterialBuy;
            });
		},

        getDept: function () {

                $("#jqGrid1").jqGrid({
                    url: baseURL + 'api/bmaterial/list',
                    datatype: "json",
                    colModel: [
                        {label: 'guid', name: 'guid', index: 'guid', width: 50, key: true, hidden: true},

                        {label: '物质编码', name: 'mCode', index: 'm_code', width: 80},
                         {label: '材料中类', name: 'mMidtype', index: 'm_midtype', width: 80},
                        {label: '材料标签', name: 'mLabel', index: 'm_label', width: 80},
                        {label: '材料名称', name: 'mName', index: 'm_name', width: 80},
                        {label: '技术参数', name: 'mParameter', index: 'm_parameter', width: 80},
                        {label: '购置单位', name: 'mUnit', index: 'm_unit', width: 80},
                        {label: '购置单价', name: 'mPrice', index: 'm_price', width: 80},

                    ],
                    viewrecords: true,
                    height: 385,
                    rowNum: 10,
                    rowList: [10, 30, 50],
                    rownumbers: true,
                    rownumWidth: 25,
                    autowidth: '100%',
                    multiselect: true,
                    pager: "#jqGridPager1",
                    jsonReader: {
                        root: "page.list",
                        page: "page.currPage",
                        total: "page.totalPage",
                        records: "page.totalCount"
                    },
                    prmNames: {
                        page: "page",
                        rows: "limit",
                        order: "order"
                    },
                    gridComplete: function () {
                        //隐藏grid底部滚动条
                        $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                    }
                })

        },
        deptTree: function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择明细",
                area: ['800px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    console.log(index)
                    var grid = $("#jqGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if (!rowKey) {
                        alert("请选择一条记录");
                        return;
                    }

                    var guids = grid.getGridParam("selarrrow");
                    console.log(guids)
                    if (guids.length > 1) {
                        alert("只能选择一条记录");
                        return;
                    }
                    $.get(baseURL + "api/bmaterial/info/" + guids[0], function (r) {
                            vm.dMaterialBuy = {



                        pGuid:GetUrlParam("pguid"),
                       pPGuid:GetUrlParam("dpguid"),
                        mMGuid:r.bMaterial.guid ,
                        mBBigtype:r.bMaterial.mBigtype,
                        mBMidtype:r.bMaterial.mMidtype,
                        mBName: r.bMaterial.mName,
                         mBParameter:r.bMaterial.mParameter,
                         mBWeight:r.bMaterial.mWeight,
                         mBPrice:r.bMaterial.mPrice,
                         mBUnit:r.bMaterial.mUnit,
                                //节假日修改
                         wiretype:r.bMaterial.wiretype,
                          wirediam:r.bMaterial.wirediam,
                          mbanktype:r.bMaterial.mbanktype,
                         mBCount:1,
                         mBWeightall:r.bMaterial.mWeight,
                         mBPriceall:r.bMaterial.mPrice,
                        mBSource:"人工",
                       mBDatastate:"新增",
                        dLabel:r.bMaterial.mLabel

                     };
					});

                    layer.close(index);
                }
            });
        },

        querymy: function () {
            var page = $("#jqGrid1").jqGrid('getGridParam','page');
            $("#jqGrid1").jqGrid('setGridParam',{
                postData: {
                    'mtype': vm.q.mtype,
                    'mName': $("#mname").val(),
                    'mBigtype':$("#mBigtype").val(),
                    'mMidtype':$("#mMidtype").val()

                },
                page:page
            }).trigger("reloadGrid");
        },

















        reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'qLabel': vm.q.qLabel,
                    'qName': vm.q.qName,
                },
                page:page
            }).trigger("reloadGrid");
		}
	}


});